import { useRequest } from 'ahooks';
import { fetchBrand, fetchSeries, fetchVersion } from '@/services/userFeedback/abnormalLog';
// import { uniqBy } from 'lodash';

const transformData = data => {
  const groupedData = new Map();

  data.forEach(item => {
    if (!groupedData.has(item.name)) {
      groupedData.set(item.name, []);
    }

    groupedData.get(item.name).push({
      value: item.code,
      label: item.code,
    });
  });

  const result = Array.from(groupedData, ([name, children]) => ({
    value: name,
    label: name,
    children,
  }));

  return result;
};

const useOptions = (form: any) => {
  const brand = useRequest(fetchBrand);

  const series = useRequest(fetchSeries, {
    manual: true,
  });

  const version = useRequest(fetchVersion);

  const handleChange = (value: string) => {
    series.run(value);
    form.resetFields(['vehicleType']);
  };

  const filter = (inputValue: string, path: any[]) =>
    path.some(
      option => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return {
    brand: brand.data,
    // series: uniqBy(series.data || [], 'name'),
    series: transformData(series.data || []),
    version: version.data,
    onChange: handleChange,
    filter
  };
};

export default useOptions;
